package com.blade.controller;

import com.blade.common.utils.ExcelUtil;
import com.blade.common.utils.MapUtil;
import com.blade.vo.AjaxResponseVO;
import com.blade.vo.ResponseCode;
import com.blade.common.utils.StaticResourceUtil;
import com.blade.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Pattern;

/**
 * excel导入导出
 */
@Controller
@RequestMapping(value = "/excel")
public class ExcelController {
    @RequestMapping
    public String index() {
        return "excel-read-write";
    }

    @ResponseBody
    @RequestMapping(value = "/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/msexcel;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 设定输出文件头
        response.setHeader("Content-disposition", "attachment;filename=" +
                URLEncoder.encode("报表文件-" + System.currentTimeMillis() + ".xls", "UTF-8"));

        List<User> userList = new ArrayList<>();
        userList.add(new User());
        userList.add(new User());
        userList.add(new User());
        userList.add(new User());
        userList.add(new User());

        ExcelUtil.writeExcel(userList, response.getOutputStream(), "用户表", MapUtil.asMap(LinkedHashMap.class,
                "userName", "会员姓名",
                "mobile", "联系方式",
                "email", "邮箱"
                ));
    }

    @ResponseBody
    @RequestMapping(value="import", method = RequestMethod.POST)
    public AjaxResponseVO importExcel(MultipartFile uploadExcel) throws Exception {
        InputStream in = uploadExcel.getInputStream();

        // 读取到表格的数据
        List<String[]> infos = ExcelUtil.readExcel(in, 1);

        // 验证表格数据的合法性
        String validateResult = validateData(infos);

        if (validateResult == null) {
            // todo 这里保存excel中拿到的infos数据到数据库

            // 备份上传的文件到本地硬盘
            saveFile(uploadExcel);

            // 保存数据成功
            return AjaxResponseVO.of(infos);
        } else {
            // 验证数据失败，返回失败消息
            return AjaxResponseVO.of(ResponseCode.FAIL.code(), validateResult, null);
        }
    }

    /**
     * 保存上传文件到本地硬盘
     * @param uploadExcel 上传的文件
     */
    private void saveFile(MultipartFile uploadExcel) throws IOException {
        File fileDir = new File(StaticResourceUtil.getResourceUploadPath("ExcelUploadPath"));
        String originalFilename = uploadExcel.getOriginalFilename();

        String fileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
        File targetFile = new File(fileDir, fileName);

        if (!targetFile.exists()) {
            // 创建保存目录
            targetFile.mkdirs();
        }

        //保存文件到硬盘
        uploadExcel.transferTo(targetFile);
    }

    /**
     * 验证导入的excel数据格式是否正确
     * @param infos 导入的表格数据
     * @return 验证的消息，通过反回null，失败反回失败消息
     */
    private String validateData (List<String[]> infos) {
        int index = 1;

        if (infos.size() == 0) {
            return "验证失败，表格里没有数据";
        }

        try{
            for (String[] user : infos) {
                if (!Pattern.matches("^1[34578]\\d{9}$", user[1])) {
                    return "第" + index + "行数据验证失败，您的值：" + user[1] + ",手机号格式错误！";
                }

                index ++;
            }
        } catch (Exception e) {
            return "导入数据异常，请检查表格数据是否正确";
        }

        return null;
    }


    public static void main(String[] strings) throws FileNotFoundException {
//        Map<String, String> map = new LinkedHashMap<>();

//        map.put("1", "1");
//        map.put("2", "2");
//        map.put("3", "3");
//        map.put("4", "4");
//        map.put("5", "5");
//        map.put("6", "6");
//        map.put("7", "7");
//        map.put("8", "8");
//
//        Set<String> keys = map.keySet();
//        for(String key : keys) {
//            System.out.println(key);
//        }

        List<User> userList = new ArrayList<>();
        userList.add(new User());
        userList.add(new User());
        userList.add(new User());
        userList.add(new User());
        userList.add(new User());

        Map<String, String> titleMap = new LinkedHashMap<>();
        titleMap.put("userName", "用户名");
        titleMap.put("mobile", "手机号");
        titleMap.put("email", "邮箱");

        List<Map<String, String>> aa = new ArrayList<>();

        Map<String, String> bb = new HashMap<>();
        Map<String, String> cc = new HashMap<>();

        bb.put("age", "11");
        bb.put("name", "33");




        cc.put("age", "444");
        cc.put("name", "666");

        aa.add(bb);
        aa.add(cc);

        Map<String, String> ttttt = new LinkedHashMap<>();
        ttttt.put("age", "岁数");
        ttttt.put("name", "名称");



        ExcelUtil.writeExcel(aa, "/Users/blade/Desktop/hhhhhh.xls", "用户表", ttttt);

    }
}
